<?php

namespace App\Http\Controllers\Admin;

use App\Http\Model\Links;
use Illuminate\Http\Request;

use App\Http\Requests;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Validator;

class LinksController extends CommonController
{
    //  get admin/links
	public function index()
	{
		$data = Links::orderBy('link_order', 'asc')->get();
		return view('admin.links.index', compact('data'));
	}

	//get admin/links/create
	public function create()
	{
		return view('admin.links.create');
	}

	//post admin/links  负责添加友情链接的存储
	public function store()
	{
		$input = Input::except('_token');
		$rules = [
			'link_name' => 'required',
			'link_url' => 'required',
		];
		$message = [
			'link_name.required' => '链接名称名称不能为空',
			'link_url.required' => '链接URL不能为空',

		];
		$validator = Validator::make($input, $rules, $message);

		if ($validator->passes()) {
			$result = Links::create($input);
			if ($result) {
				return redirect('admin/links');
			} else {
				return back()->with('errors', '链接添加失败，请稍后重试');
			}

		} else {
			return back()->withErrors($validator);
		}
	}

	//get admin/links/{links}/edit
	public function edit($link_id)
	{
		$field = Links::find($link_id);
		return view('admin.links.edit', compact('field'));
	}

	//put admin/links/{links}
	public function update($link_id)
	{
		$input = Input::except('_token', '_method');
		$result = Links::where('link_id', $link_id)->update($input);
		if ($result) {
			return redirect('admin/links');
		} else {
			return back()->with('errors', '链接更新失败，请稍后重试');
		}
	}

	//delete admin/links/{links}
	public function destroy($link_id)
	{
		$result = Links::where('link_id', $link_id)->delete();
		if ($result) {
			$data = [
				'status' => 0,
				'msg' => '链接删除成功'
			];
		} else {
			$data = [
				'status' => 1,
				'msg' => '链接删除失败'
			];
		}
		return $data;
	}

	public function changeOrder()
	{
		$input = Input::all();
		$link = Links::find($input['link_id']);
		$link->link_order = $input['link_order'];
		$result = $link->update();
		if($result) {
			$data = [
				'status' => 0,
				'msg' => '友情链接排序更新成功',
			];
		} else {
			$data = [
				'status' => 1,
				'msg' => '友情链接排序更新失败，请稍后重试',
			];
		}
		return $data;
	}

	public function show()
	{

	}
}
